package com.colin.util.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhaolz
 * @date 2023/4/27 15:02
 */
public class CanalClient {

    public static void main(String[] args) {
        // 简单demo，同官网
//        simpleDemo();
        // 表名及ID获取消费demo
        tableNameIdDemo();
    }

    private static void tableNameIdDemo() {

        // 创建连接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(
                "172.16.3.50", 11111
        ), "example", "", "");

        // 一次获取消息数量
        int batchSize = 1000;

        try {
            connector.connect();
            connector.subscribe(".*\\..*");
            connector.rollback();
            while (true) {
                // 获取指定数量的数据
                Message message = connector.getWithoutAck(batchSize);
                long batchId = message.getId();
                int size = message.getEntries().size();

                try{
                    if (batchId == -1 || size == 0) {
                        // 没有获取到消息，等待
//                        System.out.println("暂无消息，进入等待");
                        Thread.sleep(1000L);
                        continue;
                    }

                    // 获取消息
                    List<CanalEntry.Entry> entries = message.getEntries();
                    // 处理消息，获取表信息
                    Map<String, List<String>> stringListMap = parseTableNameAndId(entries);
                    // 启用线程池，处理后续业务
                    dealBusiness(stringListMap);

                }catch (Exception e){
                    e.printStackTrace();
                }

                // 提交确认，消费失败也提交，不重复消费
                connector.ack(batchId);
                // 处理失败, 回滚数据
                // connector.rollback(batchId);

            }

        } finally {
            connector.disconnect();
        }

    }

    private static void dealBusiness(Map<String, List<String>> stringListMap) {
        System.out.println(JSONObject.toJSONString(stringListMap));
    }

    private static Map<String, List<String>> parseTableNameAndId(List<CanalEntry.Entry> entrys) throws Exception {
        Map<String, List<String>> tableIdsMap = new HashMap<>();
        for (CanalEntry.Entry entry : entrys) {
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                System.out.println("事务操作，跳过了");
                continue;
            }

            // 获取数据行
            CanalEntry.RowChange rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());

            // 操作类型
            CanalEntry.EventType eventType = rowChage.getEventType();
            if(eventType != CanalEntry.EventType.INSERT && eventType != CanalEntry.EventType.UPDATE && eventType != CanalEntry.EventType.DELETE){
                // 非更新操作，不处理
                System.out.println("非更新操作不处理");
                continue;
            }

            // 表名
            String tableName = entry.getHeader().getTableName();

            // 获取操作的主键ID
            String id = null;
            for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
                if (eventType == CanalEntry.EventType.DELETE) {
                    id = getId(rowData.getBeforeColumnsList());
                } else {
                    id = getId(rowData.getAfterColumnsList());
                }
            }
            if(StringUtils.isBlank(id)){
                System.out.println("未获取到主键ID，不处理");
                continue;
            }

            System.out.printf("================table [%s]|[%s] , eventType : %s%n", tableName, id, eventType);

            List<String> ids = tableIdsMap.get(tableName);
            if(CollectionUtils.isEmpty(ids)){
                ids = new ArrayList<>();
            }
            ids.add(id);
            tableIdsMap.put(tableName, ids);
        }
        return tableIdsMap;
    }


    private static String getId(List<CanalEntry.Column> columns) {
        for (CanalEntry.Column column : columns) {
            if ("id".equals(column.getName())) {
                return column.getValue();
            }
        }
        return null;
    }

    private static void simpleDemo() {
        // 创建连接
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(
                "172.16.3.50",11111
        ),"example", "", "");

        int batchSize = 1000;
        int emptyCount = 0;
        try {
            connector.connect();
            connector.subscribe(".*\\..*");
            connector.rollback();
            int totalEmptyCount = 120;
            while (emptyCount < totalEmptyCount) {
                // 获取指定数量的数据
                Message message = connector.getWithoutAck(batchSize);
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId == -1 || size == 0) {
                    emptyCount++;
                    System.out.println("empty count : " + emptyCount);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {

                    }
                } else {
                    emptyCount = 0;
                    List<CanalEntry.Entry> entries = message.getEntries();
                    // System.out.printf("message[batchId=%s,size=%s] \n", batchId, size);
                    printEntry(entries);
                }

                // 提交确认
                connector.ack(batchId);
                // 处理失败, 回滚数据
                // connector.rollback(batchId);
            }

            System.out.println("empty too many times, exit");
        } finally {
            connector.disconnect();
        }
    }

    private static void printEntry(List<CanalEntry.Entry> entrys) {
        for (CanalEntry.Entry entry : entrys) {
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                continue;
            }

            CanalEntry.RowChange rowChage = null;
            try {
                rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
                        e);
            }

            CanalEntry.EventType eventType = rowChage.getEventType();
            System.out.println(String.format("================&gt; binlog[%s:%s] , name[%s,%s] , eventType : %s",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                    eventType));

            for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
                if (eventType == CanalEntry.EventType.DELETE) {
                    printColumn(rowData.getBeforeColumnsList());
                } else if (eventType == CanalEntry.EventType.INSERT) {
                    printColumn(rowData.getAfterColumnsList());
                } else {
                    System.out.println("-------&gt; before");
                    printColumn(rowData.getBeforeColumnsList());
                    System.out.println("-------&gt; after");
                    printColumn(rowData.getAfterColumnsList());
                }
            }
        }
    }

    private static void printColumn(List<CanalEntry.Column> columns) {
        for (CanalEntry.Column column : columns) {
            System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
        }
    }

}
